module Cip
  class Admin::PagesController < Admin::ApplicationController

    def index
      if params[:category_id]
        @category = Category.find(params[:category_id])
        @pages = @category.pages.order(:position)
      else
        redirect_to cip_admin_category_pages_path(Category.first)
      end
    end

    def show
      redirect_to edit_cip_admin_page_path(params[:id])
    end

    def new
      @category = Category.find(params[:category_id])
      @page = @category.pages.new
    end

    def create
      @page = Page.new(page_params)
      if @page.save
        redirect_to cip_admin_category_pages_path(@page.category)
      else
        render :new
      end
    end

    def edit
      @page = Page.find(params[:id])
    end

    def update
      @page = Page.find(params[:id])
      if @page.update_attributes(page_params)
        redirect_to cip_admin_category_pages_path(@page.category)
      else
        render :edit
      end
    end

    def destroy
      @page = Page.find(params[:id])
      @page.destroy if @page.category.editable
      redirect_to cip_admin_category_pages_path(@page.category)
    end

    def reorder
      positions = params[:positions]

      Page.transaction do
        positions.map do |index, position|
          page = Page.find_by(category_id: params[:category_id], position: position[:old_data])
          page.position = position[:new_data]
          page
        end.each do |page|
          page.save
        end
      end

      head :ok
    end

    private

    def page_params
      params.require(:cip_page).permit(:category_id, :title, :author, :avatar, :_destroy_avatar, :forwarding_type, :content, :forwarding_page_id, :forwarding_category_id, :forwarding_url, :slug, :position, :view_count, :template, :hint, :created_at, :disabled).tap do |whitelisted|
        if params[:cip_page][:metadata]
          whitelisted[:metadata] = params[:cip_page][:metadata].permit!
        end
      end
    end
  end
end
